package blow.sky.quoted.utils;

import blow.sky.quoted.dao.VerifyCodeDao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Description 创建验证码
 * @Author 孙焰明
 * @Date 2021/5/20 20:13
 */

@Component
public class VerifyCodeUtil
{
	@Autowired
	private VerifyCodeDao dao;
	@Value("${verify-code.time}")
	private int expireTime;

	/**
	 * 生成随机数串
	 * @param length 数串的长度
	 * @return
	 */
	private String randomNum(int length)
	{
		Random random = new Random();
		String result = "";
		for (int i=0; i < length; i++)
		{
			result += random.nextInt(10);
		}
		return result;
	}

	/**
	 * 创建验证码，5分钟内有效
	 * @param email 要使用验证码的用户
	 * @return
	 */
	public String createCode(String email)
	{
		String code = randomNum(6);
		dao.set(email, code, expireTime, TimeUnit.MINUTES);
		return code;
	}

	/**
	 * 验证 验证码
	 * @param email 使用验证码的用户
	 * @param code 验证码
	 * @return
	 */
	public boolean verifyCode(String email, String code)
	{
		String co = dao.get(email);
		if (co != null && co.equals(code))
			return true;
		else
			return false;
	}
}
